/** biome-ignore-all lint/suspicious/noExplicitAny: ignore all */
import { BaseMigration } from "@shared/triplit/migrations/base-migration";
import type { MigrationContext } from "@shared/triplit/migrations/types";

export class AddDefaultHasSequentialContentMigration extends BaseMigration {
  public readonly version = "2.2.0";
  public readonly description =
    "Add default value for hasSequentialContent field in messages";
  public readonly dependencies: string[] = ["2.1.0"];

  public async up(context: MigrationContext): Promise<void> {
    const { client, logger } = context;

    logger.info("Starting migration to add default hasSequentialContent field");

    try {
      // Update messages collection to ensure hasSequentialContent has a default value
      const messagesQuery = client.query("messages");
      const messagesResult = await client.fetch(messagesQuery);

      let messageEntities: [string, any][] = [];

      if (messagesResult instanceof Map) {
        messageEntities = Array.from(messagesResult.entries()).map(
          ([key, value]) => [String(key), value],
        );
      } else if (Array.isArray(messagesResult)) {
        messageEntities = messagesResult.map((entity) => [
          String(entity.id),
          entity,
        ]);
      } else if (messagesResult && typeof messagesResult === "object") {
        messageEntities = Object.entries(messagesResult).map(([key, value]) => [
          String(key),
          value,
        ]);
      }

      logger.info(
        `Found ${messageEntities.length} messages entities to update`,
      );

      // Update existing messages to ensure they have the hasSequentialContent field
      for (const [id, entity] of messageEntities) {
        const updates: any = {};

        // Add hasSequentialContent field if missing (default: false)
        if (
          entity.hasSequentialContent === undefined ||
          entity.hasSequentialContent === null
        ) {
          updates.hasSequentialContent = false;
        }

        if (Object.keys(updates).length > 0) {
          await client.update("messages", id, (e: any) => {
            Object.assign(e, updates);
          });
          logger.debug(
            `Updated messages entity ${id} with default hasSequentialContent value`,
          );
        }
      }

      logger.info(
        "Migration to add default hasSequentialContent field completed successfully",
      );
    } catch (error) {
      logger.error("Failed to add default hasSequentialContent field:", error);
      throw error;
    }
  }
}
